package com.netty.modbus.coder;

import com.netty.modbus.constants.Constants;
import com.netty.modbus.dto.response.*;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

import java.util.List;

/**
 * description: SecondDecoder <br>
 * date: 2021/9/30 14:59 <br>
 * @author: lwy <br>
 * @version: 1.0 <br>
 */
public class SecondDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> out) throws Exception {
        if (byteBuf.capacity() < Constants.NUM_7) {
            //报文长度小于7不操作
            return;
        }
        //封装成自建的请求体
        //取出命令字，第3个字节,起始符
        //内容
        ResponseBody responseBody;
        byte[] data = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(data);
        byte command= data[2];
        switch (command){
            case Constants.RtuFunction.COMMAND_1:
                responseBody=new RegisterBody();
                responseBody.decode(data);
                break;
            case Constants.RtuFunction.COMMAND_2:
                responseBody=new DateTimeBody();
                responseBody.decode(data);
                break;
            case Constants.RtuFunction.COMMAND_3:
                responseBody=new AlarmSettingBody();
                responseBody.decode(data);
                break;
            case Constants.RtuFunction.COMMAND_4:
                responseBody=new DataUpBody();
                responseBody.decode(data);
                break;
            case Constants.RtuFunction.COMMAND_5:
                responseBody=new ReadResponseBody(data);
                break;
            default:
                throw new IllegalStateException("Unexpected value: " + command);
        }
        out.add(responseBody);
    }
}
